package com.st.warehouse.utils;

import android.os.Handler;

import com.alibaba.fastjson.JSONObject;
import com.st.warehouse.utils.StringUtils;

import java.io.IOException;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpClientUtils {

    final public static int CONNECT_TIMEOUT_SECONDS = 5;    // 连接超时时间
    final public static int READ_TIMEOUT_SECONDS = 15;      // 读取超时时间
    final public static String COOKIE = "Cookie";

    // URL定义
//    public static String HOST_URL = "http://toolapp.sutonginfo.com:18080";  //正式
//    public static String HOST_URL = "http://47.104.179.15:18010";  // 测试
    public static String HOST_URL = "http://47.104.179.15:17102";  // 测试
//    public static String HOST_URL = "http://192.168.0.83:18010";   // 本地

    final public static String URL = "/api/park/shaoxie";   // 接口
    // CODE定义
    final public static int MSG_WHAT_ERROR = -999;  // 网络异常
    final public static int MSG_WHAT_LOGIN_SUCCESS = 1;//登录成功
    final public static int MSG_GET_SUCCESS = 2;//get
    final public static int MSG_WHAT_SEARCH_SUCCESS = 3;//查询周边成功
    final public static int MSG_WHAT_UPDATE_APK_SUCCESS = 4;//查询版本成功
    final private static HashSet<String> cookies = new HashSet<>();

    private HttpClientUtils() {
    }
    /**
     * 更新APK
     */
    public static void updateAPK(Handler handler, String code, String version) {
        OkHttpClient okHttpClient = getClient();
        JSONObject json = new JSONObject();
        json.put("code",code);
        json.put("version",version);
        RequestBody newBody = RequestBody.create(MediaType.parse("application/json"), json.toJSONString());
        Request request = new Request.Builder().url(HOST_URL.concat(URL)).post(newBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                handler.obtainMessage(MSG_WHAT_ERROR, e).sendToTarget();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONObject data = getDataFromResponse(response);
                if (handler != null)
                    handler.obtainMessage(MSG_WHAT_UPDATE_APK_SUCCESS, data).sendToTarget();
            }
        });
    }

    /**
     * get请求测试
     * @param handler
     */
    public static void getTest(Handler handler, JSONObject condition) {
        OkHttpClient okHttpClient = getClient();
        String param = "?code="+condition.get("code")+"&ver="+condition.get("ver");
        Request request = new Request.Builder().url(HOST_URL.concat(URL+param)).get().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.obtainMessage(MSG_WHAT_ERROR, e).sendToTarget();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONObject data = getDataFromResponse(response);
                if (handler != null)
                    handler.obtainMessage(MSG_GET_SUCCESS, data).sendToTarget();
            }
        });
    }
    /**
     * 查周边
     */
    public static void searchNearby(Handler handler, JSONObject condition) {
        OkHttpClient okHttpClient = getClient();
        RequestBody newBody = RequestBody.create(MediaType.parse("application/json"), condition.toJSONString());
        Request request = new Request.Builder().url(HOST_URL.concat(URL)).post(newBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.obtainMessage(MSG_WHAT_ERROR, e).sendToTarget();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONObject data = getDataFromResponse(response);
                if (handler != null)
                    handler.obtainMessage(MSG_WHAT_SEARCH_SUCCESS, data).sendToTarget();
            }
        });
    }
    public static OkHttpClient getClient() {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder().connectTimeout(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS).readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS);
        return builder.addInterceptor(new AddCookiesInterceptor()).build();
    }
    /**
     * 拦截器
     */
    static class AddCookiesInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            final Request.Builder builder = chain.request().newBuilder();
            for (String cookie : cookies) {
                builder.addHeader(COOKIE, cookie);
            }
            // TODO: 2023/11/8  添加token
            return chain.proceed(builder.build());
        }
    }
    /**
     * 获取接口返回数据
     */
    private static JSONObject getDataFromResponse(Response response) throws IOException {
        if (response != null && response.isSuccessful() && response.body() != null) {
            String responseStr = response.body().string();
            if (StringUtils.isJson(responseStr)) {
                return JSONObject.parseObject(responseStr);
            } else {
                return getErrorJson("网络异常，数据异常");
            }
        } else {
            return getErrorJson("网络异常，连接超时");
        }
    }
    /**
     * 获取报错的信息
     */
    private static JSONObject getErrorJson(String msg) {
        JSONObject data = new JSONObject();
        data.put("code", 500);
        data.put("success", false);
        data.put("msg", msg);
        return data;
    }


}